package XMLtest.stu;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class Demo {
    public Document parseXML(File file){
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            DocumentBuilder builder = fac.newDocumentBuilder();
            doc = builder.parse(file);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return doc;
    }

    //查找所有学生
    public ArrayList<Student> searchAllStus(Document doc){
        ArrayList<Student> stuList = new ArrayList<Student>();
        NodeList nl = doc.getElementsByTagName("student");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            Element e = (Element) node;

            String id = e.getAttribute("ID");
            NodeList nll = e.getElementsByTagName("name");
            Element eName = (Element) nll.item(0);
            String name = eName.getTextContent();

            Student s = new Student(id,name);
            stuList.add(s);

        }
        return stuList;
    }


    public static void main(String[] args) {

        File file = new File("src/XMLtest/stu/stu.xml");
        Demo demo = new Demo();
        Document doc = demo.parseXML(file);
        if(doc!=null){
            ArrayList<Student> stus = demo.searchAllStus(doc);
            for (Student s:stus) {
                System.out.println(s);

            }
        }
    }

}
